container_name=$1
run_env=$2
run_system=$3
run_case_path=$4

printf "容器名称为:${container_name}\n
运行环境为:${run_env}\n
运行系统为:${run_system}\n
执行用例目录为:${run_case_path}\n
"
cloudloanweb_start=$(docker ps -f name=${container_name} |awk 'NR!=1 {print $NF}')
cloudloanweb_no_start=$(docker ps -a -f name=${container_name} |awk 'NR!=1 {print $NF}')
if [ ${#cloudloanweb_start} -ge 1 ]; then
    printf "发现启动中的${container_name}容器 进行停止与删除操作 \n"
    docker stop ${container_name}
    docker rm ${container_name}
    printf "容器删除完成 \n"
elif [ ${#cloudloanweb_no_start} -ge 1 ]; then
    printf "发现未启动的$1容器 进行删除操作 \n"
    docker rm ${container_name}
else
  printf "未发现启动中与未启动的${container_name}容器 \n"
fi
printf "环境初始化完成 开始打包镜像 \n"
docker build -t ${container_name} .
printf "镜像打包完成 启动容器 \n"
docker run -e env=${run_env} -e system=${run_system} -e casepath=${run_case_path} -v /etc/localtime:/etc/localtime -i --name ${container_name} ${container_name}
printf "将docker内生成的allure报告转移到外部文件夹\n"
container_id=$(docker ps -a -f name=${container_name} |awk 'NR!=1 {print $1}')
docker cp ${container_id}:./results ./
printf "删除无效镜像并停止容器\n"
docker rmi -f  `docker images | grep '<none>' | awk '{print $3}'`
printf "镜像删除完成 \n"
docker stop ${container_name}
workspace=$PWD
printf "工作目录为:${workspace}\n"
chmod 777 ${workspace}
chmod 777 "${workspace}/results"
printf "检查容器是否正常运行完成\n"
logs=`docker logs --tail 1 ${container_name} |grep -E 'ERROR|FAILED|INTERRUPTED|NO_TESTS_COLLECTED'`
if [ -n "${logs}" ]; then
  printf "容器启动异常\n"
  exit 1
fi